<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 2019/3/29
 * Time: 17:57
 */

namespace App\Http\Controllers\VipChannel\Book;

use App\Http\Controllers\VipChannel\BaseController;
use App\Http\Controllers\VipChannel\Book\Transformers\BookTransformer;
use App\Modules\Channel\Models\ChannelUser;
use App\Modules\SendOrder\Models\SendOrderStat;
use App\Modules\Util;
use DB;
use Illuminate\Http\Request;

class BookController extends BaseController
{
    public function getDataInfo(Request $request)
    {
        $channels = $this->getDistributionChannelIds($request);
        if (count($channels) <= 0) {
            return response()->error('NOT_EXIST');
        } else {
            $result = SendOrderStat::getInfos($this->getParams($request), false);
            foreach ($result as $item) {
                $channels_str = implode(',', $channels);
                $item->order_num = $item->success_order_num + $item->unpaid_num;
                $item->charge_arup = Util::getPersentAmountInteger($item->charge_amount, $item->pay_user_num);
                $item->order_success_rate = Util::getPersentAmount($item->success_order_num, $item->order_num);
                $item->charge_amount_yesterday = $this->getYesterdayChargeAmount($item->date, $channels_str, $item->bid);
            }
            return response()->pagination(new BookTransformer(), $result);
        }
    }

    public function exportDataInfo(Request $request)
    {
        $channels = $this->getDistributionChannelIds($request);
        if (count($channels) <= 0) {
            return response()->error('NOT_EXIST');
        } else {
            $result = SendOrderStat::getInfos($this->getParams($request), true);
            $header = ['日期', '书名', '订单总数', '成功订单数', '充值总额', '派单数', '订单成功率', '昨日充值', '充值人数', '人均充值'];
            $data = [];
            foreach ($result as $item) {
                $channels_str = implode(',', $channels);
                $item->order_num = $item->success_order_num + $item->unpaid_num;
                $item->charge_arup = Util::getPersentAmountInteger($item->charge_amount, $item->pay_user_num);
                $item->order_success_rate = Util::getPersentAmount($item->success_order_num, $item->order_num);
                $item->charge_amount_yesterday = $this->getYesterdayChargeAmount($item->date, $channels_str, $item->bid);

                $data[] = array(
                    $item->date,
                    $item->book_name,
                    $item->order_num,
                    $item->success_order_num,
                    $item->charge_amount,
                    $item->send_order_number,
                    $item->order_success_rate,
                    $item->charge_amount_yesterday,
                    $item->pay_user_num,
                    $item->charge_arup
                );
            }
            saveExcelData($header, $data, '', '', '书籍数据');
        }
    }

    function getParams($request)
    {
        $end_time = $request->has('end_date') ? $request->input('end_date') : '';
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        $start_time = $request->has('start_date') ? $request->input('start_date') : '';

        if (!$start_time) {
            $start_time = date("Y-m-1", strtotime("-1 month"));
        }

        if (!$end_time) {
            $end_time = date("Y-m-d", strtotime("-1 day"));
        }

        return compact('channels', 'start_time', 'end_time', 'book_name');
    }

    function getYesterdayChargeAmount($date, $channels, $bid)
    {
        $date = date("Y-m-d", strtotime("-1 day", strtotime($date)));
        $sql = "select sum(recharge_amount) as yesterday_recharge from send_orders_force_day_stats where distribution_channel_id in ($channels) and  bid =" . $bid . " and date='" . $date . "'";
        $yesterday_recharge = DB::select($sql);
        $charge_amount_yesterday = $yesterday_recharge[0]->yesterday_recharge;
        if (!$charge_amount_yesterday) {
            $charge_amount_yesterday = 0;
        }
        return $charge_amount_yesterday;
    }

    /**
     * @param Request $request
     * @return mixed
     */
    public function getDataInfoByCatalog(Request $request)
    {
        $date = $request->has('date') ? $request->input('date') : '';
        $type = $request->has('type') ? $request->input('type') : 'site';
        $book_name = $request->has('book_name') ? $request->input('book_name') : '';
        $end_time = $request->has('end_date') ? $request->input('end_date') : '';
        $start_time = $request->has('start_date') ? $request->input('start_date') : '';
        $phone = $request->has('phone') ? $request->input('phone') : '';
        $distribution_channel_id = $request->has('distribution_channel_id') ? $request->input('distribution_channel_id') : '';
        if (!in_array($type, ['site', 'account'])) {
            return response()->error('PARAM_ERROR');
        }

        $groupBy = $type;
        $channels = $this->getDistributionChannelIds($request);

        if ($phone) {
            $channel_user = ChannelUser::getByPhone($phone);
            if ($channel_user) {
                $channels = ChannelUser::getChannelIdArray($channel_user->id);
            }
        }

        if ($distribution_channel_id) {
            $channels = explode(',', $distribution_channel_id);
        }

        if (count($channels) <= 0) {
            $result = [];
        } else {
            $params = compact('channels', 'book_name', 'date', 'groupBy', 'start_time', 'end_time');
            $result = SendOrderStat::getInfosByType($params, false);
            foreach ($result as $item) {
                $channels_str = $this->getStringChannels($item, $type);
                $item->charge_amount_yesterday = $this->getYesterdayChargeAmount($item->date, $channels_str, $item->bid);
                $item->order_num = $item->success_order_num + $item->unpaid_num;
                $item->order_success_rate = Util::getPersentAmount($item->success_order_num, $item->order_num);
                $item->charge_arup = Util::getPersentAmountInteger($item->charge_amount, $item->pay_user_num);
            }
        }
        return response()->pagination(new BookTransformer(), $result);
    }

    function getStringChannels($item, $type)
    {
        $channels_str = '';
        if ($item->bid) {
            if ($type == 'site') {
                $channels_str = $item->distribution_channel_id;
            } else {
                //如果是账号，获取这个账号下面的站点
                $channel_user = ChannelUser::getByPhone($item->phone);
                if ($channel_user) {
                    $channels = ChannelUser::getChannels($channel_user->id);
                    foreach ($channels as $channel) {
                        $channels_str = $channels_str . $channel->id . ',';
                    }
                    $channels_str = substr($channels_str, 0, strlen($channels_str) - 1);
                }
            }
        }
        return $channels_str;
    }
}